﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Rabbit.Logic;
using RabbitManage.Code;
using Raven.Imports.Newtonsoft.Json;

namespace RabbitManage.Action
{
    public partial class ShipRuleCityAdd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies[Constant.CookieName];
            string shopId = cookie.Values[Constant.CookieUid];

            Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            if (!string.IsNullOrEmpty(postContent))
            {
                try
                {
                    List<RegionCost> items = JsonConvert.DeserializeObject<List<RegionCost>>(postContent);

                    ShipRule rule = RabbitUse.GetShipRuleByShopId(Db.Store, shopId);
                    if (rule == null)
                    {
                        rule = new ShipRule();
                        rule.ShopId = shopId;
                        rule.Rules = new Dictionary<string, decimal>();
                        rule.CityRules = new Dictionary<string, decimal>();
                    }
                    else
                    {
                        if (rule.CityRules == null)
                        {
                            rule.CityRules = new Dictionary<string, decimal>();
                        }
                    }

                    foreach (var item in items)
                    {
                        rule.CityRules[item.Region] = item.Cost;
                    }

                    RabbitUse.AddShipRule(Db.Store, rule);


                    Response.Write("true");
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else
            {
                Response.Write("false");
            }
        }
    }
}